const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate;
exports.main = async (event, context) => {
	const functionName = event.functionName;
	const data = event.data;

	try {
		let result;

		if (functionName === 'addCard') {
			const {
				user_id,
				card_id,
				card_password
			} = data;
			result = await addCard(user_id, card_id, card_password);
		}else if(functionName === 'getCardInfo') {
			const {
				card_id
			} = data;
			result = await getCardInfo( card_id);
		} else {
			throw new Error('Invalid functionName');
		}

		return result;
	} catch (err) {
		throw err;
	}
};

//新增卡片信息接口
async function addCard(user_id, card_id, card_password) {

	// 检查卡号是否已存在
	const existCheck = await db.collection('jlg-card')
		.where({
			card_id: dbCmd.eq(card_id)
		})
		.count()

	if (existCheck.total > 0) {
		return {
			code: 409,
			msg: '该卡号已存在'
		}
	}

	// 写入数据库
	try {
		const res = await db.collection('jlg-card').add({
			card_id,
			card_password,
			user_id,
			create_time: Date.now(),
			is_use: false
		})

		return {
			code: 200,
			data: res.id,
			msg: '卡片录入成功'
		}
	} catch (e) {
		return {
			code: 500,
			msg: '数据库写入失败'
		}
	}
}

//获取卡片详情接口
async function getCardInfo(_id) {
	try {
	    const result = await db.collection('jlg-card')
	      .aggregate()
	      .match({ card_id:_id }) // 筛选卡片 ID 为 001 的记录:ml-citation{ref="1,2" data="citationList"}
	      .lookup({
	        from: 'uni-id-users',         // 关联用户表
	        localField: 'user_id', // 卡片表外键字段
	        foreignField: '_id',   // 用户表主键字段
	        as: 'user_info'        // 关联结果存入数组字段:ml-citation{ref="2,7" data="citationList"}
	      })
	      .addFields({
	        user_name: $.arrayElemAt(['$user_info.username', 0]) // 提取用户姓名:ml-citation{ref="2,7" data="citationList"}
	      })
	      .project({
	        user_info: 0 // 移除临时关联数组:ml-citation{ref="8" data="citationList"}
	      })
	      .end();
		if(result.length==0){
			return {
				code: 409,
				msg: '该卡号不存在'
			}
		}
		return {
			code: 200,
			data: result.data[0],
			msg: '获取卡片信息成功'
		}
	  } catch (err) {
	    console.error('查询失败:', err);
	    return { code: 500, msg: '服务端错误' };
	  }
	
}